#include <stdio.h>
#include <string.h>
#include "log.h"
#include "esmd_types.h"
#include "io_pdb.h"
#include "memory_cpp.hpp"
#include "list_cpp.hpp"
#define PDB_MAX_LINE_LEN 128
// this is only a subset of http://www.charmm-gui.org/?doc=lecture&module=pdb&lesson=1
pdb_data_t *read_pdb(FILE *fpdb) {
  pdb_data_t *pdbdat = esmd::allocate<pdb_data_t>(1, "PDB data");
  esmd::list<pdb_atom_t> atom_list("PDB atoms data");
  // esmd_list_init(&atom_list, 32, "PDB atoms data");
  char line[PDB_MAX_LINE_LEN];
  char word[PDB_MAX_LINE_LEN];
  char tmp[9];
  while (fgets(line, PDB_MAX_LINE_LEN, fpdb)) {
    if (!strncmp(line, "ATOM  ", 6)) {
      pdb_atom_t *atom = atom_list.get_slot();
      strncpy(word, line + 6, 5);
      word[5] = ' ';
      strncpy(word + 6, line + 30, 8);
      word[14] = ' ';
      strncpy(word + 15, line + 38, 8);
      word[23] = ' ';
      strncpy(word + 24, line + 46, 8);
      sscanf(word, "%s" F_GR F_GR F_GR, tmp, &atom->x, &atom->y, &atom->z);
    }
  }
  pdbdat->natom = (long)atom_list.size();
  pdbdat->atom = atom_list.extract();
  return pdbdat;
}

void free_pdb(pdb_data_t *pdb) {
  esmd::deallocate(pdb->atom);
  esmd::deallocate(pdb);
}
#ifdef TEST_PDB
int main() {
  memory_init();
  FILE *fpdb = fopen("../ubq_wb.pdb", "r");
  pdb_data_t *pdbdat = read_pdb(fpdb);
  ARR_FOR(v, pdbdat->atom, pdbdat->natom) {
    printf("%d %f %f %f\n", v->id, v->x, v->y, v->z);
  }
  memory_print();
}
#endif
